﻿using System;
using System.CodeDom.Compiler;
using System.Linq;
using Microsoft.CSharp;

namespace RuntimeHelloWorlds
{
	/// <summary>
	/// Takes a string literal of C# code, compiles it then
	/// calls it through reflection.
	/// </summary>
	public class CSharpProviderHelloWorld
	{
		public void SayHelloWorld()
		{
			CSharpCodeProvider provider = new CSharpCodeProvider();
			CompilerParameters parameters = new CompilerParameters();
			parameters.OutputAssembly = "HelloWorldCodeDomAssembly.dll";
			parameters.GenerateInMemory = true;
			parameters.GenerateExecutable = false;

			CompilerResults results = provider.CompileAssemblyFromSource(parameters, @"
namespace CSharpProviderHelloWorldNamespace
{
	public class CSharpProviderHelloWorldClass
	{
		public void HelloWorld()
		{
			System.Console.WriteLine(""Hello, World! (CSharp Code Provider)"");
		}
	}
}");
			var type = results.CompiledAssembly.GetTypes().First();
			var methodInfo = type.GetMethods().Where(m => m.Name.Contains("HelloWorld")).First();
			var obj = Activator.CreateInstance(type);
			methodInfo.Invoke(obj, null);
		}
	}
}
